package com.interceptor;

import com.entity.system.UserInfo;
import com.util.Const;
import com.util.Jurisdiction;
import com.util.LogUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * 
* 类名称：LoginHandlerInterceptor.java
* 类描述： 
* @author FH
* 作者单位： 
* 联系方式：
* 创建时间：2015年1月1日
* @version 1.6
 */
public class LoginHandlerInterceptor extends HandlerInterceptorAdapter{

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		// TODO Auto-generated method stub

 	    String path = request.getServletPath();
		if(path.matches(Const.NO_INTERCEPTOR_PATH)){
			return true;
		}else{
			String menuId = request.getParameter("menuId");
			String type = request.getParameter("type");
			//shiro管理的session
			Subject currentUser = SecurityUtils.getSubject();
			Session session = currentUser.getSession();
			UserInfo user = (UserInfo)session.getAttribute(Const.SESSION_USER);
			if(user!=null && StringUtils.isNotEmpty(menuId) && StringUtils.isNotEmpty(type)){
//				path = path.substring(1, path.length());
				boolean b = Jurisdiction.hasJurisdiction(path,menuId,type);
				if(!b){
					LogUtil.info("************没有权限************");
					if(request.getHeader("x-requested-with") != null && request.getHeader("x-requested-with").equalsIgnoreCase("XMLHttpRequest")){
						ServletOutputStream outputStream = response.getOutputStream();
						outputStream.print("1111");
						outputStream.flush();
						outputStream.close();
					}else {
						response.sendRedirect(request.getContextPath() + Const.LOGIN);
					}

				}
				return b;
			}else{
				//登陆过滤
				LogUtil.info("登录失效,跳转到登录界面");

				if(request.getHeader("x-requested-with") != null && request.getHeader("x-requested-with").equalsIgnoreCase("XMLHttpRequest")){
					ServletOutputStream outputStream = response.getOutputStream();
					outputStream.print("9999");
					outputStream.flush();
					outputStream.close();
				}else {
					response.sendRedirect(request.getContextPath() + Const.LOGIN);
				}
				return false;
				//return true;
			}
		}
	}
	
}
